# 这是一个示例 Python 脚本。

# 按 Shift+F10 执行或将其替换为您的代码。
# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。
import pandas as pd
import matplotlib.pyplot as plt
import random
import numpy as np


# 按间距中的绿色按钮以运行脚本。
def Question_1(lpl_data):
    length = 736

    # 小实例：如何通过pandas读取数据
    # rows = lpl_data.iloc[5, :]  # [行，列]
    # print(rows['gameid'])

    # Q1 match lasting time & kills

    # k/d rate
    x_spring = []
    y_spring = []
    x_summer = []
    y_summer = []

    for i in range(0, length):
        # 一场比赛的两方
        blue = lpl_data.iloc[2 * i, :]
        # red = lpl_data.iloc[2 * i + 1, :]

        # 判断赛季类型比赛时间与kd比的关系
        time = blue['gamelength']
        if blue['result'] == 0:
            y = blue['deaths'] / blue['kills']
        else:
            y = blue['deaths'] / blue['kills']
        if blue['split'] == 'Spring':
            x_spring.append(time)
            y_spring.append(y)
        else:
            x_summer.append(time)
            y_summer.append(y)

    p1 = plt.scatter(x_spring, y_spring, c='orange')
    p2 = plt.scatter(x_summer, y_summer, c='blue')
    p3 = plt.plot([0, 4000], [1, 1], c='red')

    plt.legend([p1, p2], ['Spring', 'Summer'], loc=0)
    plt.ylim(0, 8)
    plt.xlim(0, 4000)
    plt.title('relations between winning team KD and lasting time')
    plt.show()

    # total kill
    x_spring = []
    y_spring = []
    x_summer = []
    y_summer = []

    for i in range(0, length):
        # 一场比赛的两方
        blue = lpl_data.iloc[2 * i, :]
        # red = lpl_data.iloc[2 * i + 1, :]

        # 判断赛季类型比赛时间与kd比的关系
        time = blue['gamelength']
        if blue['result'] == 0:
            y = blue['deaths'] + blue['kills']
        else:
            y = blue['deaths'] + blue['kills']
        if blue['split'] == 'Spring':
            x_spring.append(time)
            y_spring.append(y)
        else:
            x_summer.append(time)
            y_summer.append(y)

    p1 = plt.scatter(x_spring, y_spring, c='orange')
    p2 = plt.scatter(x_summer, y_summer, c='blue')
    p3 = plt.plot([0, 4000], [40, 40], c='red')
    p4 = plt.plot([2500, 2500], [0, 60], c='red')

    plt.legend([p1, p2], ['Spring', 'Summer'], loc=0)
    plt.ylim(0, 60)
    plt.xlim(0, 4000)
    plt.title('relations between total kills and lasting time')
    plt.show()

    # 结论：1、KD差距较大的比赛往往在15~25min结束
    #      2、夏季赛春季赛整体差别不大
    #      3、20min后的比赛人头差距不断减小
    #      4、25min内结束 不超过40kills 是2021年lpl多数比赛的明显特征


def Question_2(lpl_data):
    length = 736

    # the winning rate of blue side of different version
    x_version = [11.01, 11.02, 11.03, 11.05, 11.06, 11.11, 11.12, 11.13, 11.14, 11.15]
    y_rate = []
    total = {}
    win = {}

    for item in x_version:
        total[item] = 0
        win[item] = 0

    for i in range(0, length):
        # 一场比赛的两方
        blue = lpl_data.iloc[2 * i, :]
        total[blue['patch']] += 1
        if blue['result'] == 1:
            win[blue['patch']] += 1

    for item in x_version:
        rate = win[item] / total[item]
        print(rate)
        y_rate.append(rate)

    plt.plot(range(1, 11, 1), y_rate, c='blue')
    plt.scatter(range(1, 11, 1), y_rate, c='red')
    plt.plot([0, 11], [0.5, 0.5], c='red', linestyle=':')
    plt.xlim(0, 11)
    plt.xticks([1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
               ('11.01', '11.02', '11.03', '11.05', '11.06', '11.11', '11.12', '11.13', '11.14', '11.15'))
    plt.xlabel('patch')
    plt.ylabel('winning rate')
    plt.title('relation between patches and blue side winning rate')
    plt.show()

    # 结论：1、失衡版本让蓝方收益更多
    #      2、胜率差距在5%以内的平衡版本占大多数
    #      3、版本利好呈现周期性


def Question_3(team_name, lpl_data):
    length = 736

    x_version = [11.01, 11.02, 11.03, 11.05, 11.06, 11.11, 11.12, 11.13, 11.14, 11.15]
    blue_rate = []
    red_rate = []
    blue_total = {}
    blue_win = {}
    red_total = {}
    red_win = {}

    for item in x_version:
        blue_total[item] = 0
        blue_win[item] = 0
        red_total[item] = 0
        red_win[item] = 0

    # 统计这支队伍红蓝方的胜率
    for i in range(0, length):
        # blue side
        blue = lpl_data.iloc[2 * i, :]
        if blue['teamname'] != team_name:
            continue
        if blue['result'] == 1:
            blue_win[blue['patch']] += 1
        blue_total[blue['patch']] += 1

    for i in range(0, length):
        # red side
        red = lpl_data.iloc[2 * i + 1, :]
        if red['teamname'] != team_name:
            continue
        if red['result'] == 1:
            red_win[red['patch']] += 1
        red_total[red['patch']] += 1

    for item in x_version:
        if blue_total[item] == 0:
            rate = 0
        else:
            rate = blue_win[item] / blue_total[item]
        print(rate)
        blue_rate.append(rate)
        if red_total[item] == 0:
            rate = 0
        else:
            rate = red_win[item] / red_total[item]
        print(rate)
        red_rate.append(rate)

    x = np.arange(10)
    total_width, n = 0.6, 2  # 柱状图总宽度，有几组数据
    width = total_width / n  # 单个柱状图的宽度
    x1 = x - width / 2  # 第一组数据柱状图横坐标起始位置
    x2 = x1 + width  # 第二组数据柱状图横坐标起始位置

    p1 = plt.bar(x1, blue_rate, width=width, color='deepskyblue')
    p2 = plt.bar(x2, red_rate, width=width, color='pink')
    plt.plot([-1, 10], [0.5, 0.5], c='red', linestyle=':')
    plt.xlim(-1, 10)
    plt.xticks(x,
               ['11.01', '11.02', '11.03', '11.05', '11.06', '11.11', '11.12', '11.13', '11.14', '11.15'])
    plt.xlabel('patch')
    plt.ylabel('winning rate')
    plt.title('relation between winning rate and patch of team ' + team_name)

    # 蓝方平均胜率折线图（Question2）
    y_rate = []
    total = {}
    win = {}

    for item in x_version:
        total[item] = 0
        win[item] = 0

    for i in range(0, length):
        blue = lpl_data.iloc[2 * i, :]
        total[blue['patch']] += 1
        if blue['result'] == 1:
            win[blue['patch']] += 1

    for item in x_version:
        rate = win[item] / total[item]
        print(rate)
        y_rate.append(rate)

    plt.plot(x1, y_rate, c='blue')
    p3 = plt.scatter(x1, y_rate, c='darkviolet')
    plt.legend([p1, p2, p3], ['Blue', 'Red', 'Average Blue rate'], loc=0)

    plt.show()

    # each team's blue winning rate and compared to the result of question Q2


def Question_4(lpl_data):
    length = 736

    gold_diff = []
    exp_diff = []

    for i in range(0, 2 * length):
        winner = lpl_data.iloc[i, :]
        if winner['split'] == 'Summer':
            break
        if winner['datacompleteness'] == 'partial' or winner['result'] == 0:
            continue
        gold_diff.append(winner['golddiffat15'])
        exp_diff.append(winner['xpdiffat15'])

    plt.scatter(gold_diff, exp_diff, c='blue')
    plt.plot([-5000, 12500], [0, 0], linestyle=':', c='red')
    plt.plot([0, 0], [-3000, 8500], linestyle=':', c='red')
    plt.plot([-5000, 12500], [-3000, 8500], c='red')
    plt.title('relation between golddiff and expdiff at 15min of winner in Spring Split')
    plt.xlabel('golddiff')
    plt.ylabel('expdiff')
    plt.xlim(-5000, 12500)
    plt.ylim(-3000, 8500)
    # golddiff/expdiff ?= 11500/17500
    plt.show()


if __name__ == '__main__':
    outfile = r'2021_lpl.csv'
    lpl_data = pd.read_csv(outfile)
    print(lpl_data)
    Question_1(lpl_data)
    Question_2(lpl_data)
    Question_4(lpl_data)
    Question_3('EDward Gaming', lpl_data)

    # 结论：1、金钱与经验的差值能够一定程度上近似为某一个线性关系，这说明他们可能是同步增长的。
    #      2、金钱与经验的作用对获胜比赛可能同等重要
    #      3、大多数比赛是在金钱和经验的共同优势下赢得的。
    #      4、前十五分钟的领先优势对赢得比赛至关重要（图中没有在前十五分钟获得任意一个方面的领先却获胜的场次只占很小一部分）

# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
